﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Diagnostics;

namespace VoxelCollision
{
    public class VoxelTester : MonoBehaviour
    {
        public bool drawLine = false;
        public Transform Cube;
        private Grid grid;
        private float size = 0.2f;
        Stopwatch stopwatch = new Stopwatch();
        void Start()
        {
            grid = new Grid();
            genMap();
        }

        Material mat;
        Material Mat
        {
            get
            {
                if (mat == null)
                {
                    mat = Cube.GetComponent<MeshRenderer>().material;
                }
                return mat;
            }
        }

        private void Update()
        {
            if (Cube != null)
            {
                //stopwatch.Restart();
                bool isIn = grid.isCollision(Cube.position, Cube.localScale);
                //stopwatch.Stop();
                //UnityEngine.Debug.Log(stopwatch.ElapsedMilliseconds);
                Mat.SetColor("_Color", isIn ? Color.red : Color.green);
            }
        }

        private void OnDrawGizmos()
        {
            if (grid != null && drawLine)
                grid.draw();
        }

        void genMap()
        {
            float maxX = 10;
            float maxY = 5;
            float maxZ = 12;
            grid.initialize(Mathf.CeilToInt(maxX / size) + 1, Mathf.CeilToInt(maxY / size) + 1, Mathf.CeilToInt(maxZ / size) + 1, this.size);
            UnityEngine.Debug.LogError(Mathf.CeilToInt(maxX / size) + "    " + Mathf.CeilToInt(maxY / size) + "     " + Mathf.CeilToInt(maxZ / size));
            float x = size * 0.5f * -1;
            float y = size * 0.5f * -1;
            float z = size * 0.5f * -1;
            int rx = 0;
            int ry = 0;
            int rz = 0;
            Vector3 halfSize = new Vector3(size * 0.5f, size * 0.5f, size * 0.5f);
            while (x <= maxX - size)
            {
                x += size;
                ++rx;
                ry = 0;
                y = size * 0.5f * -1;
                while (y <= maxY - size)
                {
                    y += size;
                    ++ry;
                    rz = 0;
                    z = size * 0.5f * -1;
                    while (z <= maxZ - size)
                    {
                        z += size;
                        ++rz;
                        Vector3 center = new Vector3(x, y, z);
                        bool isCast = Physics.CheckBox(center, halfSize);
                        //UnityEngine.Debug.Log(rx + "    " + ry + "     " + rz + "   " + isCast);
                        grid.Set(rx - 1, ry - 1, rz - 1, isCast);
                    }
                }
            }

        }

    }

}

